<?php
header("Content-type:text/html;charset=utf-8");
//------------------------------------------------------------------------------
//非IP白名单的用户不允许使用API控制台
//允许使用API 控制台的IP列表, 例：　192.168.11.* 192.168.[11-12].[1-13]
$ipList = array(
	//广州出口IP
	'121.8.156.66',
	
	//本地，内网地址
	'192.168.*.*','127.0.0.1','10.*.*.*'
);

if (!chkIpList($ipList)){
	header("HTTP/1.1 403 Forbidden");
	exit('Access deny!');
}

//------------------------------------------------------------------------------
function chkIpList($ipList){
	foreach ($ipList as $ip){
		if (ipInRange($ip)) return true;
	}
	return false;
}

function ipInRange($ipRange, $ip=null){
	$ip = $ip ? $ip : $_SERVER['REMOTE_ADDR'];
	$ckArr = explode('.', $ipRange);
	$ipArr = explode('.', $ip);
	
	for($i=0; $i<4; $i++){
		if ($ckArr[$i]=='*' || $ckArr[$i]==$ipArr[$i]) {continue;}

		if(is_numeric($ckArr[$i])){
			if ( $ckArr[$i]!=$ipArr[$i] ) {return false;}
			continue;
		}
		
		$rng = explode('-', trim($ckArr[$i], '[]'));
		if ($ipArr[$i] >= $rng[0] && $ipArr[$i] <= $rng[1] ) {continue;}
		else{
			return false;
		}
	}

	return true;
}
//------------------------------------------------------------------------------
if (isset($_POST['_apiAjaxCall'])){
	//print_r($_POST);exit;
	
	$rst = array();
	//包含API SDK 库文件
	include_once( 'php_sdk/zyapi_sdk_lib/ziyouApi_sdk.class.php' );
	//创建API实例
	$oSdk 	= new ziyouApi_sdk();
	
	//用户TOKEN的存储，单次访问有效
	class userStHander{
		var $globalTk = '';
		function userStHander(){}

		function utSet($tk){
			$this->globalTk = $tk;
			return true;
		}

		function utGet(){
			return $this->globalTk ? $this->globalTk : '';
		}

	}
	//用户状态的 hander ,注：如果get,set 指定的是字符串则当成函数处理
	$hander = new userStHander();
	$userHander = array(
		'get'=>array($hander,'utGet'),
		'set'=>array($hander,'utSet')
	);
	$oSdk->setUserHander($userHander);
	
	//设置API选项
	$oSdk->setOption(array('host'=>$_POST['apiHost'],'auth'=>$_POST['apiAuth']));
	
	
	$st = true;
	if (isset($_POST['user_name']) && $_POST['user_name'] && isset($_POST['user_pwd']) && $_POST['user_pwd']){
		$st = $oSdk->login($_POST['user_name'], $_POST['user_pwd']);
	}
	if(!$st){
		$rst['rst'] = $oSdk->lastErr();
	}else{
		
		$p = array();
		if (isset($_POST['apiParamValue']) && is_array($_POST['apiParamValue']))
		foreach ($_POST['apiParamValue'] as $k=>$v){
			strlen($_POST['apiParamVname'][$k]) && $p[$_POST['apiParamVname'][$k]] = $v;
		}
		$rst['rst'] = $oSdk->api($_POST['apiRoute'], $p, $_POST['http_method']);
 	}
 	
 	$rst['header'] = "API请求头信息：\n\n".$oSdk->http->getReqHeader()."\r\n".str_repeat('-', 100)."\r\n\nAPI响应头信息：\n\n".$oSdk->http->getReponse();

	echo json_encode($rst);exit;
}


//页面类型
if (isset($_REQUEST['_console_opt'])){
	$page_view = max(1,$_REQUEST['_console_opt']*1);
}else{
	$page_view = 1;
}
$navCss = array(
	1=>'navtitlenosel',2=>'navtitlenosel',3=>'navtitlenosel'
);
$navCss[$page_view] = 'navtitlesel'



?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<meta name="author" content="">
	<meta name="description" content="">
	<meta name="keywords" content="">
	<title>Ziyou-API Console tools</title>
	<style>
	table{
		font-size: 12px;
		border-top : 1px #ccc solid;
		border-left  : 1px #ccc solid;
	}
	td,th{
		font-size: 12px;
		border-bottom : 1px #ccc solid;
		border-right  : 1px #ccc solid;
	}
	
	.link01{
		color:#0082CB;
		padding: 2px;
		font-size: 14px;
		margin-bottom: 5px; 
		padding: 2px; height: 30px;
		border: 1px solid #0082CB;
		text-decoration: none;
	}

	a:hover {
		background: #0082CB;
		border: 1px solid #0082CB;
		color: white;
		text-decoration: none;
	}
	/**/

	
	textarea{
		border: 1px solid #0082CB;
		margin-bottom: 10px;
	}

	.parmInputVar{
		
		width: 170px;
	}
	
	.parmInputVal{
		width: 400;
	}
	
	.closeA{
		height: 25px;
		width: 30px;
		color:red;
		text-decoration: none;
	}
	
	a.navtitlesel  {
		height: 25px;
		margin-bottom: 0px;
		margin-right: 20px;
		
		color: white;
		background-color: #0082CB;
		border: 1px solid #0082CB;
		text-decoration: none;
	}
	
	a.navtitlenosel {
		height: 25px;
		margin-bottom: 0px;
		margin-right: 20px;
		
		color: #efefef;
		background-color: #aaa;
		border: 1px solid #aaa;
		text-decoration: none;
	}
	
  	
	.navtitle a{
		padding: 3px;
		padding-bottom : 1px;
		margin-left: 5px;
	}
	
	.navtitle a:hover{
		height: 25px;
		margin-bottom: 0px;
		margin-right: 20px;
		
		color: white;
		background-color: #0082CB;
		border: 1px solid #0082CB;
		text-decoration: none;
	}
	
	.viewPannelBox{
		border: 1px solid #0082CB;
		padding: 15px;
		background-color: #eee;
	}
   
   .panel_box div{
   	   margin: 3px;
   }
   .apiOption{
   	font-size: 13px;
   }
   .apiOption input,slect{
   		height: 20px;
   		margin-right: 19px;
   		border: 1px solid #ccc;
   }
   .apiOption input{
   		width: 280px;
   }
   
   from{
   	   padding: 0px;
   	   margin: 0px;
   	   border: 0px;
   }

   optgroup{
   	   margin-top: 20px;
   }
   .apiTips{
   	   padding: 5px;
   }
   
   .apiTips b,span{
   	   color: gray;
   	   font-weight: 100;
   }

	</style>

	<script src="http://www.ziyou.com/js/jquery.js" type="text/javascript"></script>
	<script src="apis.js" type="text/javascript"></script>
	<script>
	var JsonUti = {
	    //定义换行符
	    n: "\n",
	    //定义制表符
	    t: "\t",
	    //转换String
	    convertToString: function(obj) {
	        return JsonUti.__writeObj(obj, 1);
	    },
	    //写对象
	    __writeObj: function(obj //对象
	    , level //层次（基数为1）
	    , isInArray) { //此对象是否在一个集合内
	        //如果为空，直接输出null
	        if (obj == null) {
	            return "null";
	        }
	        //为普通类型，直接输出值
	        if (obj.constructor == Number || obj.constructor == Date || obj.constructor == String || obj.constructor == Boolean) {
	            var v = obj.toString();
	            var tab = isInArray ? JsonUti.__repeatStr(JsonUti.t, level - 1) : "";
	            if (obj.constructor == String || obj.constructor == Date) {
	                //时间格式化只是单纯输出字符串，而不是Date对象
	                return tab + ("\"" + v + "\"");
	            }
	            else if (obj.constructor == Boolean) {
	                return tab + v.toLowerCase();
	            }
	            else {
	                return tab + (v);
	            }
	        }
	        //写Json对象，缓存字符串
	        var currentObjStrings = [];
	        //遍历属性
	        for (var name in obj) {
	            var temp = [];
	            //格式化Tab
	            var paddingTab = JsonUti.__repeatStr(JsonUti.t, level);
	            temp.push(paddingTab);
	            //写出属性名
	            temp.push(name + " : ");
	            var val = obj[name];
	            if (val == null) {
	                temp.push("null");
	            }
	            else {
	                var c = val.constructor;
	                if (c == Array) { //如果为集合，循环内部对象
	                    temp.push(JsonUti.n + paddingTab + "[" + JsonUti.n);
	                    var levelUp = level + 2; //层级+2
	                    var tempArrValue = []; //集合元素相关字符串缓存片段
	                    for (var i = 0; i < val.length; i++) {
	                        //递归写对象
	                        tempArrValue.push(JsonUti.__writeObj(val[i], levelUp, true));
	                    }
	                    temp.push(tempArrValue.join("," + JsonUti.n));
	                    temp.push(JsonUti.n + paddingTab + "]");
	                }
	                else if (c == Function) {
	                    temp.push("[Function]");
	                }
	                else {
	                    //递归写对象
	                    temp.push(JsonUti.__writeObj(val, level + 1));
	                }
	            }
	            //加入当前对象“属性”字符串
	            currentObjStrings.push(temp.join(""));
	        }
	        return (level > 1 && !isInArray ? JsonUti.n: "") //如果Json对象是内部，就要换行格式化
	        + JsonUti.__repeatStr(JsonUti.t, level - 1) + "{" + JsonUti.n //加层次Tab格式化
	        + currentObjStrings.join("," + JsonUti.n) //串联所有属性值
	        + JsonUti.n + JsonUti.__repeatStr(JsonUti.t, level - 1) + "}"; //封闭对象
	    },
	    __isArray: function(obj) {
	        if (obj) {
	            return obj.constructor == Array;
	        }
	        return false;
	    },
	    __repeatStr: function(str, times) {
	        var newStr = [];
	        if (times > 0) {
	            for (var i = 0; i < times; i++) {
	                newStr.push(str);
	            }
	        }
	        return newStr.join("");
	    }
	};
	//apisData
	//调用API 按纽
	$(document).ready(function(){
		$("#apiCallBt").click(
			function (){
				if (!chkParam()){
					alert('请填写每一项必填参数');return false;
				}
				
				$("#rst_header").val('正在发送API请求...');
				$("#rst_json").val('正在发送API请求...');
				$.post("index.php", $("#apiCallForm").serializeArray(), function (rst){
					rst = $.parseJSON(rst);
					$("#rst_header").val(rst.header);
					$("#rst_json").val(JsonUti.convertToString(rst.rst));
					textareaView('rst_json');
				});
			}
		);
		
		$(".closeA").click(
			function (){
				closeApiParam(this);
			}
		);
		
		$("#addParam1").click(
			function (){ addApiParam(false);}
		);
		
		$("#addParam2").click(
			function (){ addApiParam(true);}
		);
		
		$("#addParam3").click(
			function (){ 
				resetApiParam();
			}
		);
		initApis();
		resetApiParam();
		
	}); 
	
	//初始化下拉菜单
	function initApis(){
		//
		var optionHtml = {};
		var lastGroup = '';
		var tmp = [];
		var tmpSt = false;
		var newGroup = '';
		
		$.each(apisData, function (k,v){
			//console.log(k);
			
			tmp = k.split('/');
			newGroup = tmp.length > 3 ? '/'+tmp[1]+'/'+tmp[2]+'/' : '/'+tmp[1]+'/'; 
			
			if (typeof optionHtml[newGroup]=='undefined'){
					optionHtml[newGroup]=['<optgroup label="'+newGroup+'">'];
			}
			/*
			if (lastGroup=='' || lastGroup!=newGroup){
				lastGroup = newGroup;
				//optionHtml[newGroup].push('<optgroup label="'+lastGroup+'">');
			}
			*/
			optionHtml[newGroup].push('<option value="'+k+'">'+k+'</option>');
		});
		
		//console.log(optionHtml);
		
		var tmpRst = [];
		$.each(optionHtml, function (k,v){
			v.push('</optgroup>');
			tmpRst.push(v.join("\n"));
		});
		
		$("#apiRoute").html(tmpRst.join("\n"));
		//console.log(optionHtml);
		//$("#apiRoute").html(optionHtml.join("\n"));
		
	}
	
	//functions lib 
	
	function changeApi(api){
		$(".paramTr").remove();
		var trHtml = [];
		$.each(apisData[api], function (n,p){
			trHtml.push(creParam(p));					
		});
		$("#paramsTable").append(trHtml.join("\n"));
		$("#textareaPanel textarea").val('');
		
		
		chgEnv();
		$("#tips_title").html(apiTitle[api][0]);
		$("#tips_policy").html(apiTitle[api][1]);
	}
	
	
	function chgEnv(){
		var url = $("#apiHost").val()+$("#apiRoute").val().substr(1)+'.'+$("#apiAuth").val();
		$("#tips_api").html(url);
	}
	
	function creParam(p){
		var isFile = (typeof p.file=='undefined') ? '' : 'file';
		var inputType = isFile ? 'file' : 'input';
		var isYes = p.yes ? 'isParamYes="1"' : 'isParamYes="0"';
		var yesTip = p.yes ? '<font color=red>true</font>' : 'false';
		var isDel = p.yes ? '' : '<a class="closeA" title="Delete" onclick="closeApiParam(this)" href="#">X</a>';
		return '<tr class="paramTr">'+
		'<td align="left" valign="middle"><input name="apiParamVname'+isFile+'[]" value="'+p.name+'" class="parmInputVar" type="input" /></td>'+
		'<td align="left" valign="middle"><input name="apiParamValue'+isFile+'[]" class="parmInputVal" '+isYes+' type="'+inputType+'" /></td>'+
		'<td align="center" valign="middle">'+isDel+'</td>'+
		'<td align="center" valign="middle">'+yesTip+'</td>'+
		'<td align="center" valign="middle">'+p.type+'</td>'+
		'<td align="left">'+p.desc+'</td>'+
		'</tr>';
	}
	
	function resetApiParam(){
		changeApi($("#apiRoute").val());
	}
	
	function closeApiParam(o){
		$(o).parent().parent().remove();
	}
	
	function addApiParam(type){
		var p = {'name':'paramName','yes':false,'type':'String','desc':'你自定义的参数'};
		if (type) p.file = 1;
		$("#paramsTable").append(creParam(p));
	}
	//检查是否有必填参数未填写
	function chkParam(){
		var rst = true;
		$(".parmInputVal").each(function (i,e){
			if ($(e).attr('isParamYes')=='1' && $(e).val()==''){
				rst = false;
				$(e).focus();
				return false;
			}
			
		});
		
		return rst;
	}
	
	
	function viewErrno(t){
		var k = t==0  ? '___' : $("#apiRoute").val();
		var ms = typeof apisErrno[k]=='undefined' ? '' :  apisErrno[k];
		var s = t==0  ? ms : ms+"\n\n全局错误码：\n"+apisErrno['___'];
		$("#rst_errno").val(s);
		textareaView('rst_errno');
	}
	
	
	function textareaView(n){
		$("#textareaPanel textarea").hide();
		$("#"+n).show();
	}
	
	
	function viewRstText(o){
		var t = o.value == '查看API交互的HTTP头信息' ? 'rst_header' : 'rst_json';
		o.value = t=='rst_json' ? '查看API交互的HTTP头信息' : '查看API调用结果';
		
		textareaView(t);
	}
	
	function noUser(){
		
	}
	
	</script>
	
</head>


<body>
<div class="navtitle">
	<center><h1>SANGUO-API Toolkits</h1></center>
	<a href="?_console_opt=1" class="<?=$navCss[1]?>">API Tools Console工具</a>
	<a href="?_console_opt=2" class="<?=$navCss[2]?>">PHP-SDK 调用说明与源码</a>
	<a href="?_console_opt=3" class="<?=$navCss[3]?>">ZiyouApi_sdk 源码</a>
	<hr size="1" style="margin-top: 0; margin-bottom: 20px;" color="blue">
</div>
<?php
	if ($page_view==1){
?>
<div class="panel_box">
	<form action="#" name="apiCallForm" id="apiCallForm">
	<input type="hidden" name="_apiAjaxCall" value="1">
	
	
	<div class="apiOption">
		<select name="apiHost" id="apiHost" style="width:80px;" onchange="chgEnv()" >
			<option value="http://dev.api.ziyou.com/">本地环境</option>
			<option value="http://vyouji.co.cc/">无线研发</option>
			<option value="http://testapi.ziyou.com/">测试环境</option>
			<option value="http://api.ziyou.com/">线上环境</option>
		</select>
		<span>接口：</span>
		<select name="apiRoute" id="apiRoute" onchange="changeApi(this.value)"  style="width:280px;margin-right: 18px;">
			
		</select>
		<span>认证：</span>
		<select name="apiAuth"  id="apiAuth" style="width:80px;" onchange="chgEnv()">
			<option value="smpauth">smpauth</option>
			<option value="debug">debug</option>
			<option value="native">native</option>
		</select>
	</div>
	
	<div class="apiOption">
		<select id="select-method" name="http_method" style="width:80px;">
			<option value="GET">GET</option>
			<option value="POST">POST</option>
			<option value="PUT">PUT</option>
			<option value="DELETE">DELETE</option>
		</select>
		<span>用户：</span>
		<input  name="user_name" id="user_name" value="ziyouapi@demo.com" type="input" />
		<span>密码：</span>
		<input  name="user_pwd"  id="user_pwd" style="width:80px;" type="password" value="" />
	</div>
	
	
	
	<div  style="margin-bottom: 20px;margin-top: 20px;">
		<a class="link01" id="addParam1" href="#">+文本参数</a>
		<a class="link01" id="addParam2" href="#">+文件参数</a>
		<a class="link01" id="addParam3" href="#">重置参数列表</a>
	</div>
	
	
	<!-- 参数容器 -->
	<div id="allParamsPanel">
		<table border="0" cellpadding="3" id="paramsTable" cellspacing="0">
		<tr>
			<td height="30" colspan="6" align="left" bgcolor="#fafafa">
				<div class="apiTips"><b>接口地址：</b><span id="tips_api"></span></div>
				<div class="apiTips"><b>功能描述：</b><span id="tips_title"></span></div>
				<div class="apiTips"><b>权限策略：</b><span id="tips_policy" style="color:red;"></span></div>
			</td>
		</tr>
		<tr>
			<th height="30" align="center" bgcolor="#eee">参数</th>
			<th align="center" bgcolor="#eee">参数值</th>
			<th align="center" bgcolor="#eee">操作</th>
			<th align="center" bgcolor="#eee">必选</th>
			<th align="center" bgcolor="#eee">类型</th>
			<th align="center" bgcolor="#eee">说明</th>
		</tr>
		
		</table>
	</div>
	
	<div  style="margin-bottom: 20px;margin-top: 20px;">
		<input id="apiCallBt" style=" height: 30px;" type="button" value="调用API,发送数据 ..."/>
		<input style=" height: 30px;" type="button" onclick="viewRstText(this)" value="查看API交互的HTTP头信息"/>
		<input style=" height: 30px;" type="button" onclick="viewErrno(1)" value="此接口相关的错误码"/>
		<!-- <input style=" height: 30px;" type="button" onclick="viewErrno(0)" value="查看全局错误码"/> -->
	</div>
	
	<div><hr size="1"></div>
	
	<div id="textareaPanel">
		<textarea id="rst_json" style="width:100%;height: 600px;"></textarea>
		<textarea id="rst_header" style="width:100%;height: 600px; background-color: #eee; display: none;"></textarea>
		<textarea id="rst_errno" style="width:100%;height: 600px; background-color: #eee; display: none;"></textarea>
	</div>
	</form>
</div>
<?php
	}
	if ($page_view==2){
?>
<div class="viewPannelBox">
<?php highlight_file('php_sdk/demo_code.php');?>
</div>
<?php
	}
	if ($page_view==3){
?>
<div class="viewPannelBox">
<?php highlight_file('php_sdk/zyapi_sdk_lib/ziyouApi_sdk.class.php');?>
</div>
<?php
	}
?>


</body>
</html>
